package com.pro.app.controller;


import com.baidu.unbiz.fluentvalidator.ComplexResult;
import com.baidu.unbiz.fluentvalidator.FluentValidator;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pro.core.util.ResponseUtil;
import com.pro.core.validator.NotNullValidator;
import com.pro.db.domain.*;
import com.pro.db.service.itf.*;
import com.pro.db.enums.EnumContentType;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.util.*;

import static com.baidu.unbiz.fluentvalidator.ResultCollectors.toComplex;

/**
 * <p>
 * 首页 前端控制器
 * </p>
 *
 * @author wanglei
 * @since 2019-12-21
 */
@RestController
@RequestMapping("/app/home")
public class GuopuHomeController {
    private final Log logger = LogFactory.getLog(GuopuHomeController.class);

    @Autowired
    private IGuopuCategoryService categoryService;

    @Autowired
    private IGuopuCategoryRichtextService richtextService;

    @Autowired
    private IGuopuBannerService bannerService;

    @Autowired
    private IGuopuSettingService settingService;

    @Autowired
    private IGuopuMessageboardService messageboardService;

    /**
     * @apiDefine home 官网接口
     *
     */

    /**
     * @api {GET} /app/home/first 1.1 官网首页及栏目
     * @apiName home first
     * @apiGroup home
     * @apiVersion 1.0.0
     * @apiDescription 接口负责人-王雷
     *
     * @apiSuccess {int} errno 结果码 0:正常返回,-1服务异常
     * @apiSuccess {String} errmsg 前端提示消息
     * @apiSuccess {Object} data 结果集
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
    {
     *     "errno": 0,
     *     "errmsg": "成功"
     * }
     */
    @GetMapping("/first")
    public Object first() {
        List<GuopuCategory> list = categoryService.list(new QueryWrapper<GuopuCategory>()
            .eq("deleted",0)
            .eq("level","L1")
            .eq("push_status",1)
            .orderByAsc("push_sort"));
        //1.获取栏目内容
        for(GuopuCategory category:list){
            category.setSubList(categoryService.list(new QueryWrapper<GuopuCategory>()
                    .eq("deleted",0)
                    .eq("pid",category.getId())
                    .eq("push_status",1)
                    .orderByAsc("push_sort")));

            category.setBannerList(bannerService.list(new QueryWrapper<GuopuBanner>()
                    .eq("deleted",0)
                    .eq("category_id",category.getId())
                    .eq("push_status",1)
                    .orderByAsc("push_sort")));
        }

        //2.获取官网配置
        List<GuopuSetting> settings = settingService.list(new QueryWrapper<GuopuSetting>()
                .eq("setting_type",1)
                .eq("deleted",0));

        //3.获取官网内容
        List<GuopuCategory> pushList = categoryService.list(new QueryWrapper<GuopuCategory>()
                .eq("deleted",0)
                .eq("level","L2")
                .eq("push_status",1)
                .eq("show_home",1)
                .orderByAsc("push_sort"));
        Map<String, Object> contents = new HashMap<>();
        for(GuopuCategory category : pushList){
            //如果是富文本
            if(category.getType().equals(EnumContentType.CONTENT_RICHTEXT.getKey())){
                GuopuCategoryRichtext richtext = richtextService.getOne(new QueryWrapper<GuopuCategoryRichtext>()
                    .eq("category_id",category.getId())
                    .eq("deleted",0)
                    .eq("push_status",1)
                    .orderByDesc("add_time"));
                List<GuopuCategoryRichtext> contentList = new ArrayList<>();
                contentList.add(richtext);
                category.setContentList(contentList);
            }else if(category.getType().equals(EnumContentType.CONTENT_ARTICLE_LIST.getKey())){
                Page<GuopuCategoryRichtext> page = new Page<>();
                page.setCurrent(1);
                page.setSize(4);
                IPage<GuopuCategoryRichtext> contentList = richtextService.page(page,
                        new QueryWrapper<GuopuCategoryRichtext>()
                    .eq("category_id",category.getId())
                    .eq("deleted",0)
                    .eq("push_status",1)
                    .orderByDesc("add_time"));
                category.setContentList(contentList.getRecords());
            }else if(category.getType().equals(EnumContentType.CONTENT_VIDEO_LIST.getKey())
                    || category.getType().equals(EnumContentType.CONTENT_IMAGE_LIST.getKey())){
                Page<GuopuCategoryRichtext> page = new Page<>();
                page.setCurrent(1);
                if(category.getType().equals(EnumContentType.CONTENT_VIDEO_LIST.getKey())){
                    page.setSize(3);
                }else {
                    page.setSize(4);
                }

                IPage<GuopuCategoryRichtext> contentList = richtextService.page(page,
                        new QueryWrapper<GuopuCategoryRichtext>()
                                .eq("category_id",category.getId())
                                .eq("deleted",0)
                                .eq("push_status",1)
                                .orderByDesc("add_time"));
                category.setContentList(contentList.getRecords());
            }
            category.setFatherCategory(categoryService.getById(category.getPid()));
        }

        Map<String, Object> data = new HashMap<>();
        data.put("categoryList", list);
        data.put("settingList", settings);
        data.put("pushList", pushList);
        return ResponseUtil.ok(data);
    }

    /**
     * @api {GET} /app/home/richtext 1.2 富文本内容
     * @apiName home richtext
     * @apiGroup home
     * @apiVersion 1.0.0
     * @apiDescription 接口负责人-王雷
     * 2.1中type为1时调用此接口获取内容
     *
     * @apiParam {int} categoryId 子栏目id
     *
     * @apiSuccess {int} errno 结果码 0:正常返回,-1服务异常
     * @apiSuccess {String} errmsg 前端提示消息
     * @apiSuccess {Object} data 结果集
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
    {
     *     "errno": 0,
     *     "errmsg": "成功"
     * }
     */
    @GetMapping("/richtext")
    public Object richtext(@NotNull Integer categoryId) {
        GuopuCategoryRichtext richtext = richtextService.getOne(new QueryWrapper<GuopuCategoryRichtext>()
                .eq("deleted",0)
                .eq("category_id",categoryId)
                .eq("push_status",1)
                .orderByAsc("push_sort"));
        if(null == richtext){
            return ResponseUtil.fail("暂无内容");
        }
        return ResponseUtil.ok(richtext);
    }

    /**
     * @api {GET} /app/home/list 1.3 内容列表
     * @apiName home list
     * @apiGroup home
     * @apiVersion 1.0.0
     * @apiDescription 接口负责人-王雷
     * 2.1中type为2/3/4时调用此接口获取内容
     *
     * @apiParam {int} categoryId 栏目id
     * @apiParam {int} [page] 页码
     * @apiParam {int} [size] 每页数量
     *
     * @apiSuccess {int} errno 结果码 0:正常返回,-1服务异常
     * @apiSuccess {String} errmsg 前端提示消息
     * @apiSuccess {Object} data 结果集
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
    {
     *     "errno": 0,
     *     "errmsg": "成功"
     * }
     */
    @GetMapping("/list")
    public Object list(@NotNull Integer categoryId,
                       @RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer size) {
        Page<GuopuCategoryRichtext> pageVo = new Page<>();
        pageVo.setCurrent(page);
        pageVo.setSize(size);
        IPage<GuopuCategoryRichtext> pList = richtextService.page(pageVo,
                new QueryWrapper<GuopuCategoryRichtext>()
                        .eq("category_id",categoryId)
                        .eq("deleted",0)
                        .eq("push_status",1)
                        .orderByDesc("add_time"));
        Map<String, Object> data = new HashMap<>();
        data.put("total", pList.getTotal());
        data.put("items", pList.getRecords());
        return ResponseUtil.ok(data);
    }

    /**
     * @api {GET} /app/home/read 1.4 内容详情
     * @apiName home read
     * @apiGroup home
     * @apiVersion 1.0.0
     * @apiDescription 接口负责人-王雷
     *
     * @apiParam {int} id 内容id
     *
     * @apiSuccess {int} errno 结果码 0:正常返回,-1服务异常
     * @apiSuccess {String} errmsg 前端提示消息
     * @apiSuccess {Object} data 结果集
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
    {
     *     "errno": 0,
     *     "errmsg": "成功"
     * }
     */
    @GetMapping("/read")
    public Object read(@NotNull Integer id) {
        GuopuCategoryRichtext category = richtextService.getById(id);
        if(null == category){
            return ResponseUtil.fail("内容不存在");
        }
        if(category.getDeleted().equals(1)){
            return ResponseUtil.fail("内容已删除");
        }
        category.setReadCount(category.getReadCount()+1);

        String categoryName = categoryService.getById(category.getCategoryId()).getName();

        GuopuCategoryRichtext prev = richtextService.getOne(new QueryWrapper<GuopuCategoryRichtext>()
                .eq("category_id",category.getCategoryId())
                .eq("push_status",1)
                .eq("deleted",0)
                .gt("id",category.getId())
            .orderByAsc("id"));
        if(null != prev){
            prev.setCategoryName(categoryName);
        }

        GuopuCategoryRichtext next = richtextService.getOne(new QueryWrapper<GuopuCategoryRichtext>()
                .eq("category_id",category.getCategoryId())
                .eq("push_status",1)
                .eq("deleted",0)
                .lt("id",category.getId())
                .orderByDesc("id"));
        if(null != next){
            next.setCategoryName(categoryName);
        }

        richtextService.updateById(category);
        Map<String, Object> data = new HashMap<>();
        data.put("currentOne", category);
        data.put("prevOne", prev);
        data.put("nextOne", next);
        return ResponseUtil.ok(data);
    }

    /**
     * @api {GET} /app/home/like 1.5 内容点赞
     * @apiName home like
     * @apiGroup home
     * @apiVersion 1.0.0
     * @apiDescription 接口负责人-王雷
     *
     * @apiParam {int} id 内容id
     *
     * @apiSuccess {int} errno 结果码 0:正常返回,-1服务异常
     * @apiSuccess {String} errmsg 前端提示消息
     * @apiSuccess {Object} data 结果集
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
    {
     *     "errno": 0,
     *     "errmsg": "成功"
     * }
     */
    @GetMapping("/like")
    public Object like(@NotNull Integer id) {
        GuopuCategoryRichtext category = richtextService.getById(id);
        if(null == category){
            return ResponseUtil.fail("内容不存在");
        }
        if(category.getDeleted().equals(1)){
            return ResponseUtil.fail("内容已删除");
        }
        if(null == category.getLikeCount()){
            category.setLikeCount(0);
        }
        category.setLikeCount(category.getLikeCount()+1);
        richtextService.updateById(category);
        return ResponseUtil.ok(category);
    }

    /**
     * @api {POST} /app/home/join 1.6 留言加盟等
     * @apiName home join
     * @apiGroup home
     * @apiVersion 1.0.0
     * @apiDescription 接口负责人-王雷
     *
     * @apiParam {String} name 姓名
     * @apiParam {String} phone 电话
     * @apiParam {String} content 留言
     *
     * @apiSuccess {int} code 结果码 0:正常返回,-1服务异常,1业务异常
     * @apiSuccess {String} message 前端提示消息
     * @apiSuccess {Object} value 结果集
     * @apiSuccess {String} bizCode 业务异常码
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
    {
     *     "errno": 0,
     *     "errmsg": "成功"
     * }
     */
    @PostMapping("/join")
    public Object join(@RequestBody GuopuMessageboard messageboard) {
        ComplexResult check = FluentValidator.checkAll()
                .on(messageboard, new NotNullValidator("信息"))
                .on(messageboard.getName(), new NotNullValidator("姓名"))
                .on(messageboard.getPhone(), new NotNullValidator("电话"))
                .on(messageboard.getContent(), new NotNullValidator("内容"))
                .doValidate()
                .result(toComplex());
        if (!check.isSuccess()) {
            //参数校验不通过，直接返回结果并提示缺少哪些参数
            return ResponseUtil.fail(check.getErrors());
        }

        messageboardService.save(messageboard);
        return ResponseUtil.ok();
    }

    /**
     * @api {GET} /app/home/contentL1 1.7 一级栏目内容
     * @apiName home contentL1
     * @apiGroup home
     * @apiVersion 1.0.0
     * @apiDescription 接口负责人-王雷
     *
     * @apiParam {int} categoryId 一级栏目ID
     *
     * @apiSuccess {int} errno 结果码 0:正常返回,-1服务异常
     * @apiSuccess {String} errmsg 前端提示消息
     * @apiSuccess {Object} data 结果集
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
    {
     *     "errno": 0,
     *     "errmsg": "成功"
     * }
     */
    @GetMapping("/contentL1")
    public Object contentL1(@NotNull Integer categoryId) {
        GuopuCategory categoryL1 = categoryService.getById(categoryId);
        if(null == categoryL1){
            return ResponseUtil.fail("一级栏目不存在");
        }

        //一级栏目的内容
        List<GuopuCategoryRichtext> contentList = new ArrayList<>();

        //推荐内容
        List<GuopuCategory> pushList = categoryService.list(new QueryWrapper<GuopuCategory>()
                .eq("deleted",0)
                .eq("pid",categoryId)
                .eq("show_home","1")
                .orderByAsc("push_sort"));
        for(GuopuCategory category : pushList){
            //如果是富文本
            if(category.getType().equals(EnumContentType.CONTENT_RICHTEXT.getKey())){
                GuopuCategoryRichtext richtext = richtextService.getOne(new QueryWrapper<GuopuCategoryRichtext>()
                        .eq("category_id",category.getId())
                        .eq("deleted",0)
                        .eq("push_status",1)
                        .orderByDesc("add_time"));
                List<GuopuCategoryRichtext> contents = new ArrayList<>();
                contents.add(richtext);
                category.setContentList(contents);
            }else if(category.getType().equals(EnumContentType.CONTENT_ARTICLE_LIST.getKey())){
                Page<GuopuCategoryRichtext> page = new Page<>();
                page.setCurrent(1);
                page.setSize(4);
                IPage<GuopuCategoryRichtext> contents = richtextService.page(page,
                        new QueryWrapper<GuopuCategoryRichtext>()
                                .eq("category_id",category.getId())
                                .eq("deleted",0)
                                .orderByDesc("add_time"));
                category.setContentList(contents.getRecords());
            }else if(category.getType().equals(EnumContentType.CONTENT_VIDEO_LIST.getKey())
                    || category.getType().equals(EnumContentType.CONTENT_IMAGE_LIST.getKey())){
                Page<GuopuCategoryRichtext> page = new Page<>();
                page.setCurrent(1);
                if(category.getType().equals(EnumContentType.CONTENT_VIDEO_LIST.getKey())){
                    page.setSize(3);
                }else {
                    page.setSize(4);
                }
                IPage<GuopuCategoryRichtext> contents = richtextService.page(page,
                        new QueryWrapper<GuopuCategoryRichtext>()
                                .eq("category_id",category.getId())
                                .eq("deleted",0)
                                .orderByDesc("add_time"));
                category.setContentList(contents.getRecords());
            }
            category.setFatherCategory(categoryL1);
        }

        //如果是富文本
        if(categoryL1.getType().equals(EnumContentType.CONTENT_RICHTEXT.getKey())){
            GuopuCategoryRichtext richtext = richtextService.getOne(new QueryWrapper<GuopuCategoryRichtext>()
                    .eq("category_id",categoryL1.getId())
                    .eq("deleted",0)
                    .eq("push_status",1)
                    .orderByDesc("add_time"));
            contentList.add(richtext);
        }else if(categoryL1.getType().equals(EnumContentType.CONTENT_ARTICLE_LIST.getKey())){
            Page<GuopuCategoryRichtext> page = new Page<>();
            page.setCurrent(1);
            page.setSize(10);
            IPage<GuopuCategoryRichtext> contents = richtextService.page(page,
                    new QueryWrapper<GuopuCategoryRichtext>()
                            .eq("category_id",categoryL1.getId())
                            .eq("deleted",0)
                            .orderByDesc("add_time"));
            contentList.addAll(contents.getRecords());
        }else if(categoryL1.getType().equals(EnumContentType.CONTENT_VIDEO_LIST.getKey())
                || categoryL1.getType().equals(EnumContentType.CONTENT_IMAGE_LIST.getKey())){
            Page<GuopuCategoryRichtext> page = new Page<>();
            page.setCurrent(1);
            page.setSize(20);
            IPage<GuopuCategoryRichtext> contents = richtextService.page(page,
                    new QueryWrapper<GuopuCategoryRichtext>()
                            .eq("category_id",categoryL1.getId())
                            .eq("deleted",0)
                            .orderByDesc("add_time"));
            contentList.addAll(contents.getRecords());
        }

        Map<String, Object> data = new HashMap<>();
        data.put("category", categoryL1);
        data.put("contentList", contentList);
        data.put("pushList", pushList);
        return ResponseUtil.ok(data);
    }


    /**
     * @api {GET} /app/home/appSetting 1.8 获取APP首页设置
     * @apiName home appSetting
     * @apiGroup home
     * @apiVersion 1.0.0
     * @apiDescription 接口负责人-王雷
     *
     * @apiSuccess {int} errno 结果码 0:正常返回,-1服务异常
     * @apiSuccess {String} errmsg 前端提示消息
     * @apiSuccess {Object} data 结果集
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
    {
     *     "errno": 0,
     *     "errmsg": "成功"
     * }
     */
    @GetMapping("/appSetting")
    public Object appSetting() {
        List<GuopuSetting> list = settingService.list(new QueryWrapper<GuopuSetting>()
                .eq("deleted",0)
                /*.eq("setting_type",2)*/);
        return ResponseUtil.ok(list);
    }

    /**
     * @api {GET} /app/home/banner 1.9 获取各栏目轮播图
     * @apiName home banner
     * @apiGroup home
     * @apiVersion 1.0.0
     * @apiDescription 接口负责人-王雷
     *
     * @apiParam {int} categoryId 栏目ID
     *
     * @apiSuccess {int} errno 结果码 0:正常返回,-1服务异常
     * @apiSuccess {String} errmsg 前端提示消息
     * @apiSuccess {Object} data 结果集
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
    {
     *     "errno": 0,
     *     "errmsg": "成功"
     * }
     */
    @GetMapping("/banner")
    public Object banner(@NotNull Integer categoryId) {
        List<GuopuBanner> pList = bannerService.list(
                new QueryWrapper<GuopuBanner>()
                        .eq("category_id",categoryId)
                        .eq("deleted",0)
                        .eq("push_status",1)
                        .orderByDesc("push_sort"));

        Map<String, Object> data = new HashMap<>();
        data.put("total", pList.size());
        data.put("items", pList);
        return ResponseUtil.ok(data);
    }
}

